import { Component, ViewChild, Injector, Output, EventEmitter, ElementRef } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { MaterialChargeServiceProxy, InventoryOfMaterialListDto, CreateOrUpdateMaterialForProductInput, MaterialForProductListDto, LocationOfMaterialListDto } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { InputSwitchModule } from 'primeng/primeng';

import * as moment from 'moment';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'editMaterialModal',
    templateUrl: './edit-material-modal.component.html'
})

export class EditMaterialModalComponent extends AppComponentBase {

    @ViewChild('createOrEditModal') modal: ModalDirective;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    material: InventoryOfMaterialListDto = new InventoryOfMaterialListDto();
    storageDateEnd: Date;

    constructor(
        injector: Injector,
        private _materialService: MaterialChargeServiceProxy
    ) {
        super(injector);
    }

    show(id: number): void {
        this.active = true;
        this.material.materialForProduct = new MaterialForProductListDto();
        this.material.locationOfMaterial = new LocationOfMaterialListDto();
        this._materialService.getMaterialChargeForEdit(id)
            .subscribe(result => {
                this.material = result;
                this.storageDateEnd = !this.material.materialForProduct.storageDateEnd || this.material.materialForProduct.storageDateEnd.year() === 1 ? undefined : this.material.materialForProduct.storageDateEnd.toDate();
                this.modal.show();
            });
    }

    save(): void {
        this.saving = true;
        var cup = new CreateOrUpdateMaterialForProductInput();
        cup.materialForProduct = this.material.materialForProduct
        this.material.materialForProduct.storageDateEnd = moment(this.storageDateEnd).add(8, 'hour');
        this._materialService.updateMaterialCharge(this.material)
            .pipe(finalize(() => this.saving = false))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
        this.active = false;
        this.modal.hide();
    }
}
